package com.zhishu.portal.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhishu.model.ExportModel;
import com.zhishu.model.Result;
import com.zhishu.model.TaskPage;
import com.zhishu.model.TaskPageParse;
import com.zhishu.model.Template;
import com.zhishu.portal.util.Const;
import com.zhishu.portal.util.ExcelUtil;

@Component
public class ExportService {

	private static Logger logger = Logger.getLogger(ExportService.class);

	@Resource
	private NutDao mysqlDao;

	public HSSFWorkbook export(Long user_id, String request_id) {
		try {
			Template t = mysqlDao.fetch(Template.class, Cnd.where("request_id", "=", request_id));
			if (t != null) {
				List<ExportModel> list = new ArrayList<ExportModel>();

				for (int i = 1; i <= t.getMax_page(); i++) {
					Result ret = this.getData(user_id, request_id, i);
					if (ret.getData() != null) {
						ExportModel exp = new ExportModel();
						exp.setList((JSONArray) ret.getData());
						exp.setHead((String[]) ret.getInfo());
						list.add(exp);
						//
					}
				}
				HSSFWorkbook wb = ExcelUtil.exportExcel(list);
				return wb;
			}
		} catch (Exception e) {
			logger.info("", e);

		}
		return null;
	}

	public Result getData(Long user_id, String request_id, Integer index) {

		Result ret = new Result();
		try {
			TaskPage job = mysqlDao.fetch(TaskPage.class,
					Cnd.where("request_id", "=", request_id).and("page", "=", index));
			if (job == null) {
				return ret;
			}
			// String requestid = job.getRequest_id();
			// int count = mysqlDao.count(TaskPage.class, Cnd.where("request_id", "=",
			// requestid));
			TaskPageParse page = mysqlDao.fetch(TaskPageParse.class,
					Cnd.where("tpid", "=", job.getId()).and("user_id", "=", user_id));
			if (page != null) {
				JSONArray array = JSONObject.parseArray(page.getResult());

				String[] ts = page.getHead().split(",");
				ret.setInfo(ts);

				ret.setData(array);
				ret.setCode(Const.SUC);
			} else {
				ret.setData(new JSONArray());
				ret.setCode(Const.SUC);
			}

			return ret;
		} catch (Exception e) {
			logger.info("", e);
			ret.setCode(Const.FAIL);

		}
		return ret;
	}

}
